﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;
using Provenance.Write.Api.Application.Command.Product;

namespace Provenance.Write.Api.Application.CommandHandler.Product
{
    public class DelProductInfoCommandHandler : IRequestHandler<DelProductInfoCommand, ApiResult>
    {
        private readonly IProductInfoRepository _productInfoRepository;
        private readonly ILogger<DelProductInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public DelProductInfoCommandHandler(IProductInfoRepository productInfoRepository, ILogger<DelProductInfoCommandHandler> logger, IMapper mapper)
        {
            _productInfoRepository = productInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(DelProductInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _productInfoRepository.GetAsync(x => x.ProductInfoId == request.ProductInfoId);
                if (obj == null)
                {
                    return ApiResult.Failure("ProductInfo not found");
                }
                obj.IsDeleted = true;
                await _productInfoRepository.DeleteEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error deleting product info: " + ex.Message);
                return ApiResult.Failure("Error deleting product info: " + ex.Message);
            }
        }
    }
}
